﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using System.Threading;
using DataCodeDemo.CamDrives;
using DataCodeDemo.Servers;
using System.Configuration;
using HalconDotNet;
using DataCodeDemo.Operators;
using System.Drawing.Imaging;

namespace DataCodeDemo
{
    public partial class Form1 : UIHeaderAsideMainFooterFrame
    {
        private bool _isOnline;
        private bool _isLive;
        private bool _isCircleTrigger;
        private bool _isSingleTrigger;
        private bool _isSetting;

        /// <summary>
        /// 相机句柄
        /// </summary>
        public uint m_handle = 0;
        private ICam _cam;
        private List<CameraInfos> cameraInfos;
        private HControlManager _halconControlManager;
        private string _path_datacode = "..\\..\\DMFile\\dm1.dcm";

        private SocketTcpServer _tcpServer = new SocketTcpServer();
        private SocketTcpClient _tcpClient = new SocketTcpClient(true);

        private string _enableServer;
        private string _localIP;
        private string _localPort;
        private string _triggerCharServer;
        private string _splitCharServer;
        private string _enableClient;
        private string _remoteIP;
        private string _remotePort;
        private string _triggerCharClient;
        private string _splitCharClient;
        private string _reConn;

        public Form1()
        {
            InitializeComponent();
            int pageIndex = 1000;
            // Aside创建Controls节点，并给对应的page标号为pageIndex
            // FMain1需要继承UIPage或者 UITitlePage
            // 将Aside和指定的Main对应关联
            //TreeNode treeNode = new TreeNode();
            FMain1 fmain1 = new FMain1() { Text = "相机1" };
            UIPage page = AddPage(fmain1, pageIndex);
            TreeNode treeNode = Aside.CreateNode(page, pageIndex + 10000, pageIndex);
            treeNode.Text = "相机1";
            // 需要将修改后的TreeNode重新装入
            Aside.SetNodeItem(treeNode, new NavMenuItem(page));

            pageIndex = 2000;
            // Aside创建Controls节点，并给对应的page标号为pageIndex
            FMain2 fmain2 = new FMain2() { Text = "相机2" };
            page = AddPage(fmain2, pageIndex);
            treeNode = Aside.CreateNode(page, pageIndex + 10000, pageIndex);
            treeNode.Text = "相机2";
            Aside.SetNodeItem(treeNode, new NavMenuItem(page));

            _cam = new DVPCamUsbDrive();
            OperateResult<List<CameraInfos>> result = _cam.GetCameras();
            if (result.IsSuccess)
            {
                cameraInfos = result.Content;
                _cam.OpenCam(cameraInfos[0]);
            }
            _halconControlManager = new HControlManager(fmain1.HWindeowControl);

            //filmShowImageControl2.ImageWatcherPath = @"C:\Users\xuan\Pictures";
        }

        private void UpdateUIControls()
        {
            btnSetting.Enabled = true;
            btnSingleTrigger.Enabled = true;
            btnCircleTrigger.Enabled = true;
            btnLive.Enabled = true;
            btnOnline.Enabled = true;
            btnCircleTrigger.Selected = false;
            btnLive.Selected = false;
            btnOnline.Selected = false;

            if (_isSetting)
            {
                btnSingleTrigger.Enabled = false;
                btnCircleTrigger.Enabled = false;
                btnLive.Enabled = false;
                btnOnline.Enabled = false;
            }
            if (_isSingleTrigger)
            {
                btnSetting.Enabled = false;
                btnSingleTrigger.Enabled = false;
                btnCircleTrigger.Enabled = false;
                btnLive.Enabled = false;
                btnOnline.Enabled = false;
            }
            if (_isCircleTrigger)
            {
                btnSetting.Enabled = false;
                btnSingleTrigger.Enabled = false;
                btnCircleTrigger.Selected = true;
                btnLive.Enabled = false;
                btnOnline.Enabled = false;
            }
            if (_isLive)
            {
                btnSetting.Enabled = false;
                btnSingleTrigger.Enabled = false;
                btnCircleTrigger.Enabled = false;
                btnLive.Selected = true;
                btnOnline.Enabled = false;
            }
            if (_isOnline)
            {
                btnSetting.Enabled = false;
                btnSingleTrigger.Enabled = false;
                btnCircleTrigger.Enabled = false;
                btnLive.Enabled = false;
                btnOnline.Selected = true;
            }
        }

        private void btnOnline_Click(object sender, EventArgs e)
        {
            string str = _isOnline ? "确定要脱机吗？" : "确定要联机吗？";
            if (ShowAskDialog(str))
            {
                _isOnline = !_isOnline;
                if (_isOnline)
                {
                    _enableServer = ConfigurationManager.AppSettings["EnableTcpServer"].ToString();
                    _localIP = ConfigurationManager.AppSettings["TcpServerIP"].ToString();
                    _localPort = ConfigurationManager.AppSettings["TcpServerPort"].ToString();
                    _triggerCharServer = ConfigurationManager.AppSettings["TcpServerTriggerChar"].ToString();
                    _splitCharServer = ConfigurationManager.AppSettings["TcpServerSplitChar"].ToString();
                    _enableClient = ConfigurationManager.AppSettings["EnableTcpClient"].ToString();
                    _remoteIP = ConfigurationManager.AppSettings["TcpClientIP"].ToString();
                    _remotePort = ConfigurationManager.AppSettings["TcpClientPort"].ToString();
                    _triggerCharClient = ConfigurationManager.AppSettings["TcpClientTriggerChar"].ToString();
                    _splitCharClient = ConfigurationManager.AppSettings["TcpClientSplitChar"].ToString();
                    _reConn = ConfigurationManager.AppSettings["TcpClientReConn"].ToString();
                    if (_enableServer == "true")
                    {
                        _tcpServer.InitSocket(_localIP, int.Parse(_localPort));
                        _tcpServer.OnRecvMsg += _tcpServer_OnRecvMsg;
                        _tcpServer.Start();
                    }
                    if (_enableClient == "true")
                    {
                        //_tcpClient = new SocketTcpClient(_reConn=="true");
                        _tcpClient.InitSocket(_remoteIP, int.Parse(_remotePort));
                        _tcpClient.OnRecvMsg += _tcpClient_OnRecvMsg;
                        _tcpClient.Start();
                    }
                }
                else
                {
                    _tcpServer.OnRecvMsg -= _tcpServer_OnRecvMsg;
                    _tcpClient.OnRecvMsg -= _tcpClient_OnRecvMsg;
                    _tcpServer?.Stop();
                    _tcpClient?.Stop();
                }
            }
            UpdateUIControls();
        }

        private void _tcpClient_OnRecvMsg(object sender, RecvMsgEventArgs e)
        {
            _tcpClient?.Send(e.Msg);
        }

        private void _tcpServer_OnRecvMsg(object sender, RecvMsgEventArgs e)
        {
            _tcpServer?.Send(e.ClientSocket, e.Msg);
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            //_isSetting = true;
            btnSetting.ShowContextMenuStrip(cmsSetting, 0, btnSetting.Height);
            UpdateUIControls();
        }

        private void btnSingleTrigger_Click(object sender, EventArgs e)
        {
            _isSingleTrigger = true;
            UpdateUIControls();
            //Thread testTh = new Thread(() =>
            //  {
            //      Thread.Sleep(1000);

            //      this.Invoke(new Action(
            //          () =>
            //          {
            //              _isSingleTrigger = false;
            //              UpdateUIControls();
            //          }
            //          ));
            //  });
            //testTh.Start();
            HImage hImage = AcqImage2();
            if (hImage.IsInitialized())
            {
                OneShot(hImage);
            }
            _isSingleTrigger = false;
            UpdateUIControls();
        }

        private void btnCircleTrigger_Click(object sender, EventArgs e)
        {
            _isCircleTrigger = !_isCircleTrigger;
            UpdateUIControls();
            if (_isCircleTrigger)
            {
                Thread circleTh = new Thread(() =>
                  {
                      while (true)
                      {
                          if (!_isCircleTrigger) break;
                          HImage hImage = AcqImage2();
                          if (hImage.IsInitialized())
                          {
                              OneShot(hImage);
                          }
                          Thread.Sleep(1);
                      }
                  });
                circleTh.Start();
            }
        }

        private void btnLive_Click(object sender, EventArgs e)
        {
            _isLive = !_isLive;
            UpdateUIControls();
            if (_isLive)
            {
                Thread liveTh = new Thread(LiveCam);
                liveTh.Start();
            }
        }

        private void btnHome_Click(object sender, EventArgs e)
        {

        }

        private void tsmCameraSetting_Click(object sender, EventArgs e)
        {
            _cam?.ShowPropertyModalDialog(Handle);
        }

        private void tsmCommucation_Click(object sender, EventArgs e)
        {

            new Form2().ShowDialog();
        }

        private void tsmTriggerSetting_Click(object sender, EventArgs e)
        {
            new FrmPhoto().ShowDialog();
        }

        private void tsmFiles_Click(object sender, EventArgs e)
        {
            new FrmFiles().ShowDialog();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _tcpServer?.Stop();
            _tcpClient?.Stop();
            Environment.Exit(0);
        }

        private string OneShot(HImage hImage)
        {
            string result = string.Empty;
            FindParams findParams = new FindParams
            {
                SqClosingRedius = 35.0,
                SqMinArea = 8000,
                SqExpansion = 20,
                PointExpansion = 8,
                FindNum = 1
            };
            _halconControlManager.HImage = hImage;
            DataCodeResult dataCodeResult = HalconOperator.FindDataCode(hImage, _path_datacode, findParams);

            if (dataCodeResult.HXLDConts.CountObj() > 0)
            {
                _halconControlManager.HXLDInfos.Add(new HXLDInfo { Color = "green", HXLD = dataCodeResult.HXLDConts, LineWidth = 5 });
                for (int i = 0; i < dataCodeResult.HXLDConts.CountObj(); i++)
                {
                    dataCodeResult.HXLDConts[i + 1].SmallestCircleXld(out double row1, out double col1, out double radius1);//计算当前线条的中心和半径
                    _halconControlManager.TextInfos.Add(new TextInfo
                    {
                        Color = "green",
                        Text = dataCodeResult.DecodedDataStrings.TupleSelect(0),
                        Location = new Point((int)(row1 + radius1), (int)col1)
                    });//添加要显示的文字

                    if (i == 0)
                    {
                        result = dataCodeResult.DecodedDataStrings.TupleSelect(0);
                    }
                    else
                    {
                        result += "," + dataCodeResult.DecodedDataStrings.TupleSelect(i);
                    }
                }

            }
            hImage?.Dispose();
            GC.Collect();
            return result;
        }

        private HImage AcqImage2()
        {
            HImage hImage = new HImage();
            if (_cam == null) return hImage;
            OperateResult<Bitmap> result = _cam.AcquireImage2();
            
            if (result.IsSuccess)
            {
                Bitmap bitmap = result.Content;
                Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadWrite, bitmap.PixelFormat);
                if (bitmapData.PixelFormat == PixelFormat.Format8bppIndexed)
                {
                    hImage.GenImage1("byte", bitmap.Width, bitmap.Height, bitmapData.Scan0);
                }
                else if (bitmapData.PixelFormat == PixelFormat.Format24bppRgb)
                {
                    hImage.GenImageInterleaved(bitmapData.Scan0, "bgr", bitmap.Width, bitmap.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
                }
                else hImage?.Dispose();
                bitmap.UnlockBits(bitmapData);
                bitmap?.Dispose();
            }
            else
            {
                hImage?.Dispose();
            }
            return hImage;
        }

        private void LiveCam()
        {
            while (true)
            {
                if (!_isLive) break;
                HImage hImage = AcqImage2();
                if (hImage.IsInitialized())
                {
                    _halconControlManager.HImage = hImage;
                }
                Thread.Sleep(1);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        
    }
}
